package com.cjm.algorithm.leetcode;

import java.util.Deque;
import java.util.LinkedList;

public class EvalRPN150 {
    public static int evalRPN(String[] tokens) {
        Deque<Integer> queue = new LinkedList<>();
        for (int i = 0; i < tokens.length; i++) {
            if (isNumber(tokens[i])) {
                queue.push(Integer.parseInt(tokens[i]));
            }else {
                Integer right = queue.pop();
                Integer left = queue.pop();
                switch (tokens[i]) {
                    case "+":
                        int res = left + right;
                        queue.push(res);
                        break;
                    case "-":
                        res = left - right;
                        queue.push(res);
                        break;
                    case "*":
                        res = left * right;
                        queue.push(res);
                        break;
                    case "/":
                        res = left / right;
                        queue.push(res);
                        break;
                    default:
                        break;
                }
            }
        }
        return queue.pop();
    }

    private static boolean isNumber(String sign) {
        try {
            Integer.parseInt(sign);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        evalRPN(new String[] {"2","1","+","3","*"});
    }
}
